package utils.version6;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 1.上一版本版本的ConnectionUtil类实现了事务功能以及得到连接的功能，我们可以把这两块功能进行拆分，拆分为ConnectionFactory和TransactionManager类型
 *
 * 2.为了与Spring的类比，把这个两个类的静态方法都改为实例方法（spring中默认是单例模式）
 */
public class ConnetionFactory {

    private static final String driverClassName = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/demo";
    private static final String username = "root";
    private static final String password = "root";

    static {
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    //这里不去掉static，这是正确的使用ThreadLocal的方式。
    private static final ThreadLocal<Connection> connectionMap = new ThreadLocal<>();

    public  Connection getCurrentConnection() {
        Connection connection = connectionMap.get();
        try {
            if (connection == null || connection.isClosed()) {
                connection = DriverManager.getConnection(url, username, password);
                connectionMap.set(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


    public  void close() {
        try {
            getCurrentConnection().close();
            connectionMap.remove(); //针对ThreadLocal实现
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
